package com.yazi.mxz.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yazi.mxz.common.Config;



@Controller("commonAttachmentController")
@RequestMapping("/at")
public class AttachmentController {

	@RequestMapping("/**")
	public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String uri = request.getRequestURI();
		uri = uri.substring(uri.indexOf("/at/") + 3);
		
	  String filePathName = Config.getInstance().getUploadPath() + uri;
	  File file = new File(filePathName);
	  response.setContentLength((int)file.length());
	  response.setHeader("Accept-Type", "bytes");
	  
	  InputStream is = new FileInputStream(file);
	  OutputStream os = response.getOutputStream();
	  byte[] b = new byte[1024];
	  int i;
	  while((i = is.read(b)) > -1) {
		  os.write(b, 0, i);
	  }
	  is.close();
	  os.close();
	}
}
